package com.csdemos.algs;

import java.util.Arrays;

public class Stack {
	
	private static final int INITIAL_SIZE = 4;
	
	private int[] S;
	private int top;
	
	public Stack() {
		this(INITIAL_SIZE);
	}
	
	public Stack(int initialSize) {
		S = new int[initialSize];
		top = 0;
	}
	
	public boolean isEmpty() {
		return top == 0;
	}
	
	public void push(int x) {
		if (top == S.length) {
			increaseSize();
		}
		top++;
		S[top - 1] = x;
	}
	
	public int pop() {
		if (isEmpty()) {
			throw new IllegalStateException("Underlow");
		}
		top--;
		return S[top];
	}
	
	private void increaseSize() {
		int oldSize = S.length;
		int newSize;
		if (oldSize == 0) {
			newSize = INITIAL_SIZE;
		} else {
			newSize = 2 * S.length;
		}
		S = Arrays.copyOf(S, newSize);
	}
	
	@Override
	public String toString() {
		StringBuilder result = new StringBuilder("[");
		for (int i = 0; i < S.length; ++i) {
			if (i == top) {
				result.append(" | ");
			}
			result.append(S[i]).append(" ");
		}
		return result.append("]").toString();
	}

}
